<template>

  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getQuery">

            <el-button slot="append" icon="el-icon-search" @click=getQuery></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-Button type="primary" @click="addDialogVisible=true">添加用户</el-Button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userlist">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="100px"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色" width="100px"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template v-slot='scope'>
            <el-switch v-model="scope.row.mg_state" @change="changeStart(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="操作">
          <template v-slot={row}>

            <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(row)"></el-button>
            <el-button v-if="row.id !==500" type="danger" size="mini" icon="el-icon-delete" @click="removeUser(row.id)">
            </el-Button>
            <el-tooltip content="角色管理" placement="top" :enterable="false">
              <el-button type="warning" size="mini" icon="el-icon-setting" @click="setRole(row)">
              </el-button>
            </el-tooltip>
          </template>

        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1,2,3,4,5]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">

      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog @close="resetAddForm" title="添加" :visible.sync="addDialogVisible" width="50%">
      <el-form ref="addFormRef" label-width="70px" :model="addForm" :rules="addFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog @close="resetEditForm" title="更新" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFormRef" label-width="70px" :model="editForm" :rules="addFormRules">
        <el-form-item label="用户名" prop="username">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="分配角色" :visible.sync="setRolelogVisible" width="50%" @close="setRoleDialogClosed">
      <div>
        <p>姓名：{{userInfo.username}}</p>
        <p>角色：{{userInfo.role_name}}</p>
        <p>分配新角色
          <el-select v-model="selectRoleId" placeholder="请选择新角色">
            <el-option v-for="obj in roleList" :key="obj.id" :label="obj.roleName" :value="obj.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolelogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    const validateEmail = (rules, val, cb) => {
      const reg = /^([a-zA-Z0-9._-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (reg.test(val)) {
        cb()
      } else {
        cb(new Error('邮箱不符合格式'))
      }
    }
    const validateMobile = (rules, val, cb) => {
      const reg1 = /^1[3456789]\d{9}$/
      if (reg1.test(val)) {
        cb()
      } else {
        cb(new Error('手机号不符合格式'))
      }
    }
    return {
      selectRoleId: '',
      roleList: [],
      userInfo: {},
      setRolelogVisible: false,
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        email: [
          { validator: validateEmail, trigger: 'blur', required: true }

        ],
        mobile: [
          { validator: validateMobile, trigger: 'blur', required: true }

        ]
      },
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      userlist: [],
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false
    }
  },
  methods: {
    setRoleDialogClosed () {
      this.selectRoleId = ''
      this.userInfo = {}
    },
    async setRoleInfo () {
      if (!this.selectRoleId) {
        return this.$Message.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectRoleId })
      if (res.meta.status !== 200) return this.$Message.error('更新角色失败')
      this.$Message.success('更新角色成功')
      this.getQuery()
      this.setRolelogVisible = false
    },
    async setRole (userInfo) {
      this.userInfo = userInfo
      // console.log(this.userInfo)
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      this.setRolelogVisible = true
    },
    removeUser (id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`users/${id}`)
        console.log(res.meta)
        console.log(res)
        if (res.meta.status !== 200) return this.$Message.error('删除失败')
        this.$Message.success('删除成功')
        this.getQuery()
      }).catch(() => {
        this.$Message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    editUser () {
      this.$refs.editFormRef.validate(async bool => {
        if (!bool) return this.$Message.error('校验失败')
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) return this.$Message.error('更新失败')
        this.$Message.success('更新成功')
        this.editDialogVisible = false
        this.getQuery()
      })
      this.editDialogVisible = false
    },
    resetEditForm () {
      this.$refs.editFormRef.resetFields()
    },
    showEditDialog (row) {
      this.editDialogVisible = true
      this.editForm = row
    },
    addUser () {
      this.$refs.addFormRef.validate(async bool => {
        if (!bool) return this.$Message.error('校验失败')
        const { data: res } = await this.$http.post('users', this.addForm) // 发起post请求
        if (res.meta.status !== 201) this.$Message.error('添加失败')
        this.$Message.success('添加成功')
        this.addDialogVisible = false // 把页面关闭
        this.getQuery() // 重新渲染页面
      })
    },
    resetAddForm () {
      this.$refs.addFormRef.resetFields()
    },
    async changeStart (row) {
      // console.log(row)

      const { data: res } = await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      // console.log(res)
      if (res.meta.status !== 200) {
        this.row.mg_state = !this.row.mg_state
        return this.$Message.error('更新数据失败')
      }
      this.$Message.success('更新数据成功')
      // console.log(this.$message)
      // console.log(11)
    },
    handleCurrentChange (current) {
      this.queryInfo.pagenum = current
      this.getQuery()
    },
    handleSizeChange (size) {
      this.queryInfo.pagesize = size
      this.getQuery()
    },
    async getQuery () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      // console.log(res.data)
      this.userlist = res.data.users
      this.total = res.data.total
      // console.log(this.userlist)
      // console.log(this.total)
    }
  },
  computed: {},
  watch: {},
  filters: {},
  components: {},
  created () {
    this.getQuery()
  },
  mounted () { }
}
</script>

<style scoped lang='less'>
.el-table {
  margin: 15px, 0;
}
</style>
